package net.qunzhi.modules.ysweixin.controller;

import net.qunzhi.common.utils.R;
import net.qunzhi.config.WaterNetworkConfig;
import net.qunzhi.modules.weixin.config.WxMpProperties;
import net.qunzhi.modules.ysweixin.entity.Button;
import net.qunzhi.modules.ysweixin.entity.ScancodePushButton;
import net.qunzhi.modules.ysweixin.entity.SubButton;
import net.qunzhi.modules.ysweixin.entity.ViewButton;
import net.qunzhi.modules.ysweixin.service.WxService;
import net.qunzhi.modules.ysweixin.utils.WxUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;


@Api(tags = "微信原生公众号接口")
@RestController
@RequestMapping("ysweixin/WxController")
public class WxController {
    @Autowired
    private WxMpProperties wxMpProperties;
    private String appId;
    private String secret;
    private String hostName;
    @Autowired
    private WaterNetworkConfig waterNetworkConfig;
    @Autowired
    private WxMpService wxMpService;

    @PostConstruct
    public void init() {
        appId = wxMpProperties.getConfigs().get(0).getAppId();
        secret = wxMpProperties.getConfigs().get(0).getSecret();
        hostName = wxMpProperties.getConfigs().get(0).getHostName();
    }

    /**
     * 用于测试微信接入用的
     *
     * @return
     */
    @GetMapping("wx")
    public R testWx(HttpServletRequest request, HttpServletResponse response) {
    	/*
    	 * 参数	描述
			signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
			timestamp	时间戳
			nonce	随机数
			echostr	随机字符串
			    	 */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        //验证消息的确来自微信服务器
        if (WxService.checkSignature(timestamp, nonce, signature)) {
            System.out.println("接入成功");
            try {
                PrintWriter out = response.getWriter();
                //原样返回echostr
                out.print(echostr);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    @ApiOperation("获得accessToken")
    @PostMapping("getAccessToken")
    public R getAccessToken() {
        String accessToken = WxService.getAccessToken(appId, secret);
        return R.ok().put("AccessToken", accessToken);
    }

    /**
     * lwh
     * 创建公众号菜单步骤，
     * 1.针对公众号的结构修改好菜单。
     * 2.然后再修改跳转的地址。
     * 3.登录本地http://localhost:8080/waterOperation/swagger-ui.html#/ 修改菜单
     * 4.微信可能有缓存修改后需要重新关注公众号测试
     */
    @ApiOperation("慎点，会对公众号重构菜单")
    @PostMapping("createMenu")
    public R createMenu() throws WxErrorException {
        String urlPrefix = "http://"+hostName+"/waternetwork/wechat/authorize?returnUrl=";
        String urlPrefix2 = "http://" + hostName;

        //菜单对象
        Button bt = new Button();
        //第一个有子菜单的菜单
        ViewButton sb1 = new ViewButton("供水管网", urlPrefix + urlPrefix2 + "/Index");
        bt.getButton().add(sb1);
        JSONObject jsonObject = JSONObject.fromObject(bt);
        System.out.println(jsonObject.toString());
        String result = wxMpService.switchoverTo(appId).getMenuService().menuCreate(jsonObject.toString());
        return R.ok().put("result", result);
    }

    @ApiOperation("获取该公众号的行业信息")
    @GetMapping("getBusiness")
    public R getBusiness() {
        String accessToken = WxService.getAccessToken(appId, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=ACCESS_TOKEN";
        String business = WxUtils.get(url.replace("ACCESS_TOKEN", accessToken));
        return R.ok().put("business", business);
    }

    @ApiOperation("获取该公众号的行业模板信息")
    @GetMapping("getBusinessTemplete")
    public R getBusinessTemplete() {
        String accessToken = WxService.getAccessToken(appId, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN";
        String businessTemplete = WxUtils.get(url.replace("ACCESS_TOKEN", accessToken));

        return R.ok().put("businessTemplete", businessTemplete);
    }

    @ApiOperation("发送模板消息")
    @PostMapping("sendTempleteMessage")
    public R sendTempleteMessage() {
        String accessToken = WxService.getAccessToken(appId, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        url = url.replace("ACCESS_TOKEN", accessToken);
        String data = "{\r\n" +
                "           \"touser\":\"o8876wkXBdLRttSaNDwhBaFf9PLQ\",\r\n" +
                "           \"template_id\":\"ZnS3BU3k0QomLiFKLGiMA_nmqC1teeZ58Uv58nZcAnE\",\r\n" +
                "           \"url\":\"http://www.baidu.com\",  \r\n" +
                "           \"data\":{\r\n" +
                "                   \"first\": {\r\n" +
                "                       \"value\":\"您有新故障工单，请及时查看！\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   },\r\n" +
                "                   \"keyword1\":{\r\n" +
                "                       \"value\":\"某学校某宿舍\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   },\r\n" +
                "                   \"keyword2\": {\r\n" +
                "                       \"value\":\"学生名字\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   },\r\n" +
                "                   \"keyword3\": {\r\n" +
                "                       \"value\":\"1300000000\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   },\r\n" +
                "                   \"keyword4\": {\r\n" +
                "                       \"value\":\"1300000000\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   },\r\n" +
                "                   \"keyword5\": {\r\n" +
                "                       \"value\":\"1300000000\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   },\r\n" +
                "                   \"remark\": {\r\n" +
                "                       \"value\":\"请及时联系及处理哦！\",\r\n" +
                "                       \"color\":\"#173177\"\r\n" +
                "                   }\r\n" +
                "           }\r\n" +
                "       }";
        String post = WxUtils.post(url, data);
        System.out.println(post);
        return R.ok();
    }

    /**
     * 获取用户的信息
     *
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getUserInfo")
    public R getUserInfo(String openId) {
        String at = WxService.getAccessToken(appId, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        url = url.replace("ACCESS_TOKEN", at).replace("OPENID", openId);
        String string = WxUtils.get(url);
        return R.ok().put("string", string);
    }

}
